package club.kingyin.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.StringUtils;

public class AspectUtils {

    public static JSONObject getParams(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        StringBuilder paramsSb = new StringBuilder();
        String params;
        for (Object arg : args) {
            paramsSb.append(JSON.toJSONString(arg));
        }

        params = paramsSb.toString();
        return JSON.parseObject(params);
    }

    public static String generateParams(ProceedingJoinPoint point) {
        Object[] args = point.getArgs();
        StringBuilder paramsSb = new StringBuilder();
        String params;
        for (Object arg : args) {
            paramsSb.append(JSON.toJSONString(arg));
        }

        params = paramsSb.toString();
        return params;
    }

    // 单个参数对象
    public static <T> T paramsObjectOne(ProceedingJoinPoint joinPoint, Class<T> tClass) {
        return tClass.cast(JSONObject.parseObject(paramsJSONString(joinPoint), tClass));
    }

    private static String paramsJSONString(ProceedingJoinPoint joinPoint) {
        //准备参数
        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        //对应放一起
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        String  parameters = params.toString()+"}";
        return parameters;
    }
}
